#!/bin/bash

  outputfile=output.txt
  exec 3> $outputfile
  >$outputfile #clear the file

## Global variables ##
  USAGE="Usage: $0 <inputfile>"
  inputfile=
  wordlengthfreq=wordLengthFreq.txt
  gnuplotsettings=wordFrequency.gnup
  gnuplotconfig=
	isdict=islensku_ordalisti.txt
  endict=/usr/share/dict/words
  totalwords=0
  totalwords_en=0
  totalwords_is=0
  totalwords_na=0
	pct_is_words=
  pct_en_words=
  pct_na_words=
  longestword_is=0
  total_is_wordlength=0
  averagewordlen_is=
  declare -A iswords
  declare -A wlfreq
  wlfreq=([2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=0 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0) 
## END OF Global variables ##

## Functions ##

function read_dict() {

  if [ `grep -c [åäöÅÄÖþÞðÐæÆáÁéÉóÓíÍúÚ] $inputfile` -eq 0 ]; then 
    echo "encoding is scandinavian"
    recode ISO-8859-1..UTF-8 $inputfile
  fi 

	while read line
  do
		iswords=([${line}]="${line}")
	done < $isdict		

	for i in ${!iswords[@]}
	do
  	echo $i
	done
}

function toupper() {
  local inupper=`echo $1|tr "[a-záðéíóúýþæö]" "[A-ZÁÐÉÍÓÚÝÞÆÖ]"`
	echo $inupper
}

function get_pct() {
		div=$2
		if [ $div == 0 ]; then
			div=1;
		fi
		echo "$(echo "scale=$3;$1*100/$div"|bc)"
} ## END OF get_pct() ##
 
function checkParams() {

  while getopts ":w:" opt; do
      case $opt in
        w)
					setFile wordlengthfreq $OPTARG
          ;;
        \?)
          echo "Invalid option: -$OPTARG" 1>&2
          ;;
      esac
    done

    shift $((OPTIND-1))
    args=("$@")

    if [ "$#" == "1" ]; then
      setFile inputfile ${args[0]}
    else
      echo $USAGE 1>&2
      exit 1
    fi

} ## END OF checkparams() ##

function setFile() {
  if [ -r $2 ]; then
    local cmd="$1=$2"
	  eval $cmd
	else
    echo "Could not read file: $2" 1>&2
    exit 1
  fi
} ## END OF setFile ##

function readInputfile() {
		for word in `cat $1|tr -cs ""[a-záðéíóúýþæöA-ZÁÐÉÍÓÚÝÞÆÖ]"" "\n"`
    do
			is=`grep -i "^$word\$" $isdict`
			en=`grep -i "^$word\$" $endict`

			if [ ! -z "$is" ]; then
        echo $is
				totalwords_is=$(($totalwords_is + 1))
				total_is_wordlength=$(($total_is_wordlength + ${#word}))
				wlfreq[${#word}]=$((${wlfreq[${#word}]} + 1))
				if [[ ${#word} > $longestword_is ]]; then
					longestword_is=${#word}
				fi
			elif [ ! -z "$en" ]; then
				totalwords_en=$(($totalwords_en + 1))
			#else [[ -z "$en" ]] && [[ -z "$is" ]]; then
			else 
				totalwords_na=$(($totalwords_na + 1))
      fi
			is=
			en=
		done
} ## END OF readInputfile() ##

function createReport() {

	totalwords=$(($totalwords_is + $totalwords_en + totalwords_na))
	echo "-- Report --"
	echo "Inputfile: $inputfile"
  echo "Total number of words: $totalwords"
  echo "Total number of icelandic words: $totalwords_is"
  echo "Percentage of icelandic words: $(get_pct $totalwords_is $totalwords 2)%"
	echo "Longest icelandic word: $longestword_is"
  echo "Average icelandic word length: $(($total_is_wordlength / $totalwords_is))"
  echo "Total number of english words: $totalwords_en"
  echo "Percentage of english words: $(get_pct $totalwords_en $totalwords 2)%"
  echo "Total number of unknown words: $totalwords_na"
  echo "Percentage of unknown words: $(get_pct $totalwords_na $totalwords 2)%"
} ## END OF createReport() ##

function createFrequencyList() {
  for i in {2..28}
  do
		local length_pct=$(get_pct ${wlfreq[$i]} $totalwords_is 5)
    echo -e "$i\t$length_pct" 1>&3
  done
} #END OF createFrequencyList() ##

function readGnuplotConfig() {
gnuplotconfig=$( cat <<EOF
set terminal postscript eps monochrome "Helvetica" 14
set output 'wordFrequency.eps'
set size 1,1
set noclip points
set clip one
set noclip two
set border
set dummy x,y
set format x "%g"
set format y "%g"
set nogrid
set nolabel
set noarrow
set nologscale
#set logscale
#set logscale y
set offsets 0, 0, 0, 0
set nopolar
set angles radians
set noparametric
set key
set samples 100
set isosamples 10
set surface
set nocontour
set cntrparam order 4
set cntrparam linear
set cntrparam points 5
set style data steps
set style function lines
set autoscale
set tics in
set ticslevel 0.5
set ytics 5
#set xtics 10
set notime
set xlabel "Word length in characters"
set ylabel "Word frequency %"
set yrange [ : ]
set xrange [1: ]
set autoscale r
set autoscale t
set key top right
set zero 0
#set datafile separator ";"
set obj 1 rectangle behind from screen 0,0 to screen 1,1
set obj 1 fillstyle solid 1.0 fillcolor rgbcolor "white"
plot\
"${outputfile}" using 1:2 title 'Current file' with linespoints ls 1 pt 7, "${wordlengthfreq}" using 1:2 title 'Dictionary' with linespoints ls 1 pt 4
 
reset
EOF
)
}

function createPlot() {
  readGnuplotConfig
  
  gnuplot << EOF
${gnuplotconfig}
EOF
 	convert -density 300 wordFrequency.eps wordFrequency.png
  rm wordFrequency.eps
} ## END OF createPlot() ##

## END OF Functions ##

## Main ##

checkParams "${@}"
#read_dict
readInputfile $inputfile
createReport
createFrequencyList
createPlot

## END OF Main ##
